﻿using D.Medicalcare.Write.API.Dtos;
using D.Medicalcare.Write.API.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;

namespace D.Medicalcare.Write.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly IDatabase _redisDatabase;

        public TestController(IConnectionMultiplexer redis)
        {
            _redisDatabase = redis.GetDatabase();
        }

        [HttpPost("pay")]
        public async Task<IActionResult> ProcessPayment([FromBody] PaymentRequest request)
        {
            // 创建分布式锁
            var lockKey = $"PaymentLock:{request.OrderId}"; // 锁的键，基于订单 ID
            var distributedLock = new RedisDistributedLock(_redisDatabase, lockKey);

            try
            {
                // 尝试获取锁
                if (await distributedLock.AcquireLockAsync())
                {
                    Console.WriteLine("已获取锁，正在处理付款...");

                    // 模拟支付处理
                    bool paymentSuccess = await ProcessPaymentAsync(request.UserId, request.OrderId, request.Amount);

                    if (paymentSuccess)
                    {
                        return Ok(new { Message = "付款成功!" });
                    }
                    else
                    {
                        return BadRequest(new { Message = "付款失败!" });
                    }
                }
                else
                {
                    return Conflict(new { Message = "正在处理此订单的另一个付款请求..." });
                }
            }
            finally
            {
                // 释放锁
                await distributedLock.ReleaseLockAsync();
            }
        }

        private async Task<bool> ProcessPaymentAsync(int userId, int orderId, decimal amount)
        {
            Thread.Sleep(1000 * 10);//模拟耗时的操作  10秒 
            Console.WriteLine($"用户ID:{userId},订单ID:{orderId},订单金额:{amount}");
            return true;
        }
    }
}
